package org.yray.sip.handler;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.yray.sip.base.*;
import org.yray.sip.config.sip.ExtTable;
import org.yray.sip.creator.MessageCreator;
import org.yray.sip.server.SipServerContext;
import org.yray.sip.server.SipSession;

@Slf4j
public class RegisterHandler extends MessageHandler {


    @Override
    public String[] handler(SipMsg sipMsg, SipServerContext ssc) {
        SipSession sipSession=SipSession.createRegisterSession(sipMsg,ssc.getRunIp(),ssc.getRunPort());
        //验密码
        if(sipMsg.isNeedAuth())
        {
            String line=sipMsg.getSipMap().get(MsgEle.AUTHORIZATION);
            Authorization authorization=new Authorization(line,MsgEle.AUTHORIZATION);
            String ext=authorization.getEleMap().get(Authorization.USERNAME);
            String password= ExtTable.findPasswordByExt(ext);
            authorization= AuthUtils.encryption(authorization,password);
            String resp=authorization.getEleMap().get(Authorization.RESPONSE);
            if(line.indexOf(resp)>-1)
            {
                log.info("password ok");
                String result= MessageCreator.getCreator(MsgType.OK).createMsg(sipSession);
                return new String[]{result};
            }
            else
            {
                log.error("err password,line={},resp{}",line,resp);
                String result= MessageCreator.getCreator(MsgType.FORBIDDEN).createMsg(sipSession);
                return new String[]{result};

            }

        }

        String result= MessageCreator.getCreator(MsgType.UNAUTHORIZED).createMsg(sipSession);
        return new String[]{result};
    }

}
